package Pet.Management.service.impl;

import Pet.Management.domain.PetCareOffer;
import Pet.Management.domain.entity.PetCareOrder;
import Pet.Management.repository.PetCareOfferRepository;
import Pet.Management.repository.PetCareOrderRepository;
import Pet.Management.service.PetCareOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class PetCareOrderServiceImpl implements PetCareOrderService {

    // 订单状态常量
    private static final int STATUS_PENDING = 0;    // 待处理
    private static final int STATUS_IN_PROGRESS = 1; // 进行中
    private static final int STATUS_COMPLETED = 2;   // 已完成
    private static final int STATUS_CANCELLED = 3;   // 已取消

    @Autowired
    private PetCareOrderRepository petCareOrderRepository;

    @Autowired
    private PetCareOfferRepository petCareOfferRepository;

    @Override
    @Transactional
    public PetCareOrder createOrder(PetCareOrder order) {
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setStatus(STATUS_PENDING);
        order.setAcceptTime(LocalDateTime.now());
        return petCareOrderRepository.save(order);
    }

    @Override
    @Transactional
    public PetCareOrder acceptOffer(Long offerId) {
        // 1. 查找并验证 offer
        PetCareOffer offer = petCareOfferRepository.findById(offerId)
                .orElseThrow(() -> new RuntimeException("Offer not found"));

        if (!"pending".equals(offer.getStatus())) {
            throw new RuntimeException("Offer is not in pending status");
        }

        // 2. 更新 offer 状态
        offer.setStatus("accepted");
        petCareOfferRepository.save(offer);

        // 3. 创建新订单
        PetCareOrder order = new PetCareOrder();
        order.setPublisherId(offer.getDemandUserId());
        order.setAcceptorId(offer.getAcceptorId());
        order.setPetName(offer.getPetName());
        order.setPetType(offer.getPetType());
        order.setServiceType("pet_care"); // 设置服务类型
        order.setStartTime(offer.getServiceStartTime());
        order.setEndTime(offer.getServiceEndTime());
        order.setPrice(offer.getPrice());
        order.setDescription(offer.getDescription());
        order.setStatus(STATUS_IN_PROGRESS);
        order.setAcceptTime(LocalDateTime.now());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        return petCareOrderRepository.save(order);
    }

    @Override
    public PetCareOrder getOrderById(Long id) {
        return petCareOrderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Order not found"));
    }
} 